const Vue = require('vue')
const express = require('express')
const renderer = require('vue-server-renderer').createRenderer()

const server = express()

server.get("/", (req, res) => {
    const app = new Vue({
        template: `
          <div id="app">
            <h1>{{ message }}</h1>
          </div>
        `,
        data: {
            message: '我是malred'
        }
    })

    // 渲染为纯文本字符串
    renderer.renderToString(app, (err, html) => {
        if (err) {
            res.status(500).end('Internal Server Error.')
            return
        }
        // html发送到客户端
        // 防止中文乱码
        res.setHeader('Content-Type','text/html; charset=utf8')
        // res.end(html)
        res.end(`
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <!--编码-->
                <meta charset="UTF-8">
                <title>Title</title>
            </head>
            <body>
                ${html}
            </body>
            </html>
        `)
    })
})

server.listen(3001, () => {
    console.log('server running at port 3001.')
})